package com.wealth.system.web.controller;

import iaas.utils.RedirectMessage;
import iaas.web.Servlets;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.member.entity.Address;
import com.wealth.member.service.IAddressService;
import com.wealth.system.entity.SSQ;
import com.wealth.system.service.ISSQService;
import com.wealth.system.service.ShiroMember;

/** 
 * 地址维护
 * @author CHAN
 */
@Controller
@RequestMapping(value="/manage/address")
public class AddressController extends BaseController{
	
	Logger logger = Logger.getLogger(AddressController.class);
	
	@Autowired
	private IAddressService addressService;
	@Autowired
	private ISSQService ssqService;
	
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getAddress(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try {
			if (id != -1) {
				Address address = addressService.getAddress(id);
				model.addAttribute("address", address);
			}
		} catch (Exception e) {
			logger.error("准备方法出错", e);
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping
	public String list(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "pageSize", defaultValue ="10") int pageSize,
			@RequestParam(value = "sortType", defaultValue = "isDefault") String sortType,
			@RequestParam(value = "sortDirection", defaultValue = "desc") String sortDirection,
			Model model,
			ServletRequest request) {
		try {
			//查询
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
			//Long memberid = ShiroMember.getInstance().getMember().getId();
			Page<Address> page = addressService.getAddress(memberid, searchParams, pageNumber, pageSize, sortType, sortDirection);
			
			//查询条件返回页面
			model.addAttribute("page", page);
			model.addAttribute("sortType", sortType);
			model.addAttribute("sortDirection", sortDirection);
			model.addAttribute("pageNumber", pageNumber);
			model.addAttribute("pageSize", pageSize);
			// 将搜索条件编码成字符串，用于排序，分页的URL
			model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
	
			return "address/list";
		} catch (Exception e) {
			logger.error("收货地址列表错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/select")
	public String select(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "pageSize", defaultValue ="5") int pageSize,
			@RequestParam(value = "sortType", defaultValue = "isDefault") String sortType,
			@RequestParam(value = "sortDirection", defaultValue = "desc") String sortDirection,
			Model model,
			ServletRequest request) {
		try {
			//查询
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
			Long memberid = ShiroMember.getInstance().getMember().getId();
			Page<Address> page = addressService.getAddress(memberid, searchParams, pageNumber, pageSize, sortType, sortDirection);
			
			//查询条件返回页面
			model.addAttribute("page", page);
			model.addAttribute("sortType", sortType);
			model.addAttribute("sortDirection", sortDirection);
			model.addAttribute("pageNumber", pageNumber);
			model.addAttribute("pageSize", pageSize);
			// 将搜索条件编码成字符串，用于排序，分页的URL
			model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
	
			return "address/select";
		} catch (Exception e) {
			logger.error("选择收货地址列表错误", e);
			return "system/500";
		}
	}
	
	
	/**
	 * 详情
	 */
	@ResponseBody
	@RequestMapping(value="/{id}")
	public Address addressInfo(Model model,@PathVariable("id") Long id){
		Address address = new Address();
		try {
			address =addressService.getAddress(id);
			return address;
		} catch (Exception e) {
			logger.error("会员收货地址详情错误,id="+id, e);
			return address;
		}
	}
	
	/**
	 * 省市区JSON
	 */
	@ResponseBody
	@RequestMapping(value="/ssq/{pid}",method = RequestMethod.GET)
	public List<SSQ> ssq(Model model,@PathVariable("pid") Long pid){
		List<SSQ> provinceList = new ArrayList<SSQ>();
		try {
			provinceList = ssqService.getSSQ(pid);
			return provinceList;
		} catch (Exception e) {
			logger.error("省市级联错误,父节点pid="+pid, e);
			return provinceList;
		}
	}
	
	
	/**
	 * 新增页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(Model model,HttpServletRequest request){
		try {
			List<SSQ> provinceList = ssqService.getSSQ(0L,0L);
			model.addAttribute("provinceList", provinceList);
			if(request.getParameter("prevurl")!=null){
				model.addAttribute("prevurl", request.getParameter("prevurl"));
			}
			return "address/create";
		} catch (Exception e) {
			logger.error("新增收货地址页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,Address address,HttpServletRequest request,RedirectAttributes redirectAttributes){
		try {
			//获得默认地址
			if(address.getIsDefault()==1){
				Address temp = addressService.getAddressDefault(ShiroMember.getInstance().getMember().getId());
				if(temp!=null){
					temp.setIsDefault(0);
					addressService.updateAddress(temp);
				}
			}
			addressService.saveAddress(address);
			
			redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipSuccess("新增地址成功"));
			if(request.getParameter("prevurl")!=null){
				return "redirect:/"+request.getParameter("prevurl");
			}
			return "redirect:/manage/address";
		} catch (Exception e) {
			logger.error("新增收货地址错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String updateForm(Model model,HttpServletRequest request ,@PathVariable("id") Long id){
		try {
			
			Address address = addressService.getAddress(id);
			List<SSQ> provinceList = ssqService.getSSQ(0L,0L);
			List<SSQ> cityList = ssqService.getSSQ((long)130000);
			List<SSQ> areaList = ssqService.getSSQ((long)130100);
			model.addAttribute("address", address);
			model.addAttribute("provinceList", provinceList);
			model.addAttribute("cityList", cityList);
			model.addAttribute("areaList", areaList);
			
			if(request.getParameter("prevurl")!=null){
				model.addAttribute("prevurl", request.getParameter("prevurl"));
			}
			return "address/update";

		} catch (Exception e) {
			logger.error("收货地址编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String addressUpdate(Model model,HttpServletRequest request, RedirectAttributes redirectAttributes,
			@ModelAttribute("address") Address address,@PathVariable("id") Long id){
		try {
			
			//获得默认地址
			if(address.getIsDefault()==1){
				Address temp = addressService.getAddressDefault(ShiroMember.getInstance().getMember().getId());
				if(temp!=null){
					temp.setIsDefault(0);
					addressService.updateAddress(temp);
				}
			}
			addressService.updateAddress(address);
			redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipSuccess("编辑地址成功"));
			if(request.getParameter("prevurl")!=null){
				return "redirect:/"+request.getParameter("prevurl");
			}
			return "redirect:/manage/address";
		} catch (Exception e) {
			logger.error("编辑收货地址错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String addressUpdate(Model model,RedirectAttributes redirectAttributes,@PathVariable("id") Long id){
		try {
			addressService.deleteAddress(id);
			redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipSuccess("删除地址成功"));
			return "redirect:/manage/address";
		} catch (Exception e) {
			logger.error("删除收货地址错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 设置该订单的收货地址
	 * 这里会将这个地址设置成用户的默认收货地址
	 * FIXME 应在缓存中设置该订单的默认地址
	 */
	@RequestMapping(value="/send/{id}",method = RequestMethod.GET)
	public String send(Model model,HttpServletRequest request,HttpSession session,@PathVariable Long id){
		try {
			
			//将默认地址设置为普通地址
			Address temp = addressService.getAddressDefault(ShiroMember.getInstance().getMember().getId());
			if(temp!=null){
				temp.setIsDefault(0);
				addressService.updateAddress(temp);
			}
			
			//设置该新地址为默认地址
			Address address = addressService.getAddress(id);
			address.setIsDefault(1);
			addressService.updateAddress(address);
			return "redirect:/manage/order/create";
		} catch (Exception e) {
			logger.error("设置订单的收货地址出错,id="+id, e);
			return "system/500";
		}
	}
	
}
